import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { nanoid } from 'nanoid';
import { Button, Form, Input, message, Radio, Spin } from 'antd';
import DraggableModal from '@/components/DraggableModal';
import DebounceWrapper from '@/components/DebounceWrapper';
import { fetchAvailableDictChildList } from '@/services/system/dictionary';
import { addSysConfigItem, updateSysConfigItem } from '@/services/system/configuration';

const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 17 },
};
const { Group } = Radio;
const DebounceButton = DebounceWrapper(Button);

export default ({ visible, options, closeModal, updateList }) => {
  const { id } = options;
  const [form] = Form.useForm();
  const [initialLoading, setInitialLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);
  const [modifyInitLoadingId, setModifyInitLoadingId] = useState('');
  const [sysConfigStatus, setSysConfigStatus] = useState([]);
  const formList = [
    {
      name: 'configName',
      label: '参数名称',
      initialValue: '',
      rules: [],
      component: Input,
      componentProps: {
        maxLength: 16,
        allowClear: true,
        placeholder: '请输入参数名称',
        autoComplete: 'off',
      },
    },
    {
      name: 'configKey',
      label: '参数键名',
      initialValue: '',
      rules: [],
      component: Input,
      componentProps: {
        maxLength: 16,
        allowClear: true,
        placeholder: '请输入参数键名',
        autoComplete: 'off',
      },
    },
    {
      name: 'configValue',
      label: '参数键值',
      initialValue: '',
      rules: [],
      component: Input,
      componentProps: {
        maxLength: 32,
        allowClear: true,
        placeholder: '请输入参数键值',
        autoComplete: 'off',
      },
    },
    {
      name: 'configType',
      label: '系统内置',
      initialValue: null,
      rules: [],
      component: Group,
      componentProps: {},
      componentChildren: sysConfigStatus.map((item) => (
        <Radio key={item.value} value={item.value}>
          {item.label}
        </Radio>
      )),
    },
  ];
  // 获取字典数据
  const getDictData = async (dictType) => {
    try {
      const res = await fetchAvailableDictChildList({ dictType });
      return _.isArray(res)
        ? _.filter(
            _.map(res, ({ dictValue, dictLabel }) => ({ value: dictValue, label: dictLabel })),
            ({ value }) => _.isString(value) || _.isNumber(value),
          )
        : [];
    } catch (e) {
      return [];
    }
  };
  // 初始化字典状态字典
  useEffect(() => {
    getDictData('sys_config').then((configStatus) => {
      setInitialLoading(false);
      setSysConfigStatus(configStatus);
    });
  }, []);
  // 表单更新
  useEffect(() => {
    if (visible) {
      if (id) {
        const { avatarPathId } = options;
        const defaultValue = _.pick(options, [
          'configName',
          'configKey',
          'configValue',
          'configType',
        ]);
        if (avatarPathId) {
          const nextModifyInitLoadingId = nanoid(12);
          setModifyInitLoadingId(nextModifyInitLoadingId);
        } else {
          form.setFieldsValue(defaultValue);
        }
      }
      return;
    }
    form.resetFields();
    setModifyInitLoadingId('');
  }, [visible]);
  const handleCancel = () => {
    if (!actionLoading) {
      closeModal();
    }
  };
  const handleConfirm = () => {
    setActionLoading(true);
    form
      .validateFields()
      .then((values) => {
        const params = _.assign(
          id ? { id: id } : {},
          _.pick(values, ['configName', 'configKey', 'configValue', 'configType']),
        );
        // console.log(params, 'params');
        const confirmAction = params.id ? updateSysConfigItem : addSysConfigItem;
        confirmAction(params)
          .then(() => {
            closeModal();
            updateList && updateList();
            setActionLoading(false);
            message.success(`配置${params.id ? '修改' : '新增'}成功`);
          })
          .catch(() => {
            setActionLoading(false);
          });
      })
      .catch(() => {
        setActionLoading(false);
      });
  };
  return (
    <DraggableModal
      // width={480}
      visible={visible}
      title={`配置${id ? '编辑' : '添加'}`}
      onCancel={handleCancel}
      footer={[
        <DebounceButton key="cancel" disabled={actionLoading} onClick={closeModal}>
          取消
        </DebounceButton>,
        <DebounceButton
          key="confirm"
          type="primary"
          loading={actionLoading}
          onClick={handleConfirm}
        >
          提交
        </DebounceButton>,
      ]}
    >
      <Spin spinning={initialLoading || !!modifyInitLoadingId} tip={'初始化..'}>
        <Form {...layout} form={form} name="config-form">
          {formList.map((item, index) => (
            <Form.Item
              {..._.pick(item, ['name', 'label', 'rules', 'initialValue', 'validateTrigger'])}
            >
              {item.component
                ? React.createElement(
                    item.component,
                    { ...item.componentProps },
                    item.componentChildren,
                  )
                : null}
            </Form.Item>
          ))}
        </Form>
      </Spin>
    </DraggableModal>
  );
};
